<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="5" :xs="24">
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入分类名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin:0 10px 20px 0;width:200px;"
            @keyup.enter.native="getDeviceType"
          />
          <el-button type="primary" icon="el-icon-search" size="mini" @click="getDeviceType" v-hasPermi="['equipmentGL:equipmentFL:search']">搜索</el-button>
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="19" :xs="24">
        <div class="app-container">
          <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="110px">
            <el-form-item label="设备分类编码" prop="deviceCode">
              <el-input v-model="queryParams.deviceCode" placeholder="请输入设备分类编码" clearable size="small"/>
            </el-form-item>
            <el-form-item label="设备分类名称" prop="deviceName">
              <el-input v-model="queryParams.deviceName" placeholder="请输入设备分类名称" clearable size="small"/>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="getList" v-hasPermi="['equipmentGL:equipmentFL:search']">搜索</el-button>
            </el-form-item>
          </el-form>
          <el-row :gutter="10" class="mb8">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="add" v-hasPermi="['equipmentGL:equipmentFL:add']">新增</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="del" v-hasPermi="['equipmentGL:equipmentFL:delete']">删除</el-button>
            <el-button type="warning" icon="el-icon-download" size="mini" @click="exportList" v-hasPermi="['equipmentGL:equipmentFL:export']">导出</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="refresh">刷新</el-button>
          </el-row>
          <el-table v-loading="loading" :data="list.rows?list.rows:list" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="序号" type="index" width="55" align="center"/>
            <el-table-column label="设备分类编码" align="center" prop="deviceCode"/>
            <el-table-column label="设备分类名称" align="center" prop="deviceName"/>
            <el-table-column label="上级" align="center" prop="parentId">
              <tempate slot-scope="scope">
                <template v-if="scope.row.parentId==0">无</template>
                <template v-else>{{filtration(scope.row.parentId)}}</template>
              </tempate>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-edit" @click="edit(scope.row)" v-hasPermi="['equipmentGL:equipmentFL:edit']">修改</el-button>
                <el-button size="mini" type="text" icon="el-icon-delete" @click="del(scope.row)" v-hasPermi="['equipmentGL:equipmentFL:delete']">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            :total="list.total?list.total:0"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
          <!-- 添加或修改设备类型表对话框 -->
          <el-dialog :title="addForm.id?'编辑':'新增'" :visible.sync="addVisible" width="600px" append-to-body>
            <el-form class="form" :model="addForm" ref="addForm" :inline="true" label-width="130px">
              <el-form-item label="上级：">
                <el-select v-model="parentName" placeholder="请选择" ref="selectReport" clearable>
                  <el-option :value="addForm.parentId" :label="parentName" style="height: auto;">
                    <el-tree :data="deptOptionsNew" :props="defaultProps" @node-click="treeClick"></el-tree>
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="设备分类名称：" prop="deviceName"
                            :rules="[{required: true, message: '请输入设备分类名称', trigger: 'blur'}]">
                <el-input size="small" v-model="addForm.deviceName" placeholder="请输入设备分类名称" clearable/>
              </el-form-item>
              <el-form-item label="设备分类编号：" prop="deviceCode"
                            :rules="[{required: true, message: '请输入设备分类编号', trigger: 'blur'}]">
                <el-input size="small" v-model="addForm.deviceCode" placeholder="请输入设备分类编号" clearable/>
              </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="submitForm">确 定</el-button>
              <el-button @click="addVisible=false">取 消</el-button>
            </div>
          </el-dialog>
        </div>
      </el-col>
    </el-row>

  </div>
</template>

<script>
  import {
    deviceType,
    deviceTypeList,
    deviceTypeParent,
    deviceTypeAdd,
    deviceTypeEdit,
    deviceTypeDel,
    deviceTypeExport
  } from '@/api/device/index'

  export default {
    name: '',
    data() {
      return {
        loading: false,
        // 选中数组
        ids: [],
        single: true,// 非单个禁用
        multiple: true,// 非多个禁用
        list: [],// 设备类型表表格数据
        addVisible: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          deviceCode: undefined,
          deviceName: undefined,
          parentId: 0
        },
        isParent: false,
        parentName: undefined,
        // 部门树选项
        deptOptions: undefined,
        deptOptionsNew: undefined,
        // 部门名称
        deptName: undefined,
        // 状态数据字典
        statusOptions: [],
        defaultProps: {
          children: 'list',
          label: 'deviceName'
        },
        addForm: {
          deviceCode: '',
          deviceName: '',
          parentId: ''
        }
      }
    },
    watch: {
      // 根据名称筛选部门树
      deptName(val) {
        this.$refs.tree.filter(val)
      }
    },
    created() {
      this.getDeviceType()
      this.getList()
    },
    methods: {
      /** 查询下拉树结构 */
      async getDeviceType() {
        let res = await deviceType({deviceName:this.deptName})
        this.deptOptions = res.rows
        this.deptOptionsNew = res.rows
      },
      // 筛选节点
      filterNode(value, data) {
        if (!value) return true
        return data.label.indexOf(value) !== -1
      },
      // 节点单击事件
      handleNodeClick(data) {
        this.queryParams.parentId = data.id
        this.getList()
      },
      /** 查询设备类型表列表 */
      async getList() {
        this.loading = true
        this.list = []
        let res = await deviceTypeList(this.queryParams)
        this.list = res
        this.loading = false
      },
      refresh() {
        this.queryParams.parentId = 0
        this.getList()
      },
      // 节点单击事件
      treeClick(data) {
        this.addForm.parentId = data.id
        this.parentName = data.deviceName
        this.$refs.selectReport.blur()
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length != 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      add() {
        delete this.addForm.id
        Object.assign(this.$data.addForm, this.$options.data().addForm)
        this.addForm.parentId = ''
        this.parentName = ''
        this.addVisible = true
      },
      /** 修改按钮操作 */
      edit(row) {
        this.addForm = {
          id: row.id,
          deviceCode: row.deviceCode,
          deviceName: row.deviceName,
          parentId: row.parentId
        }
        this.parentName = this.filtration(row.parentId)
        this.addVisible = true
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs['addForm'].validate(async(valid) => {
          if (valid) {
            if (!this.addForm.parentId) {
              this.addForm.parentId = 0
            }
            this.addForm.id ? await deviceTypeEdit(JSON.stringify(this.addForm)) : await deviceTypeAdd(JSON.stringify(this.addForm))
            this.addForm.id ? this.$message.success('编辑成功') : this.$message.success('新增成功')
            this.addVisible = false
            this.getDeviceType()
            this.getList()
          }
        })
      },
      /** 删除按钮操作 */
      del(row) {
        const ids = row.id || this.ids
        this.$confirm('确定删除吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          await deviceTypeDel(ids)
          this.$message.success('删除成功')
          if (this.isParent) {
            this.queryParams.parentId = 0
          }
          this.getDeviceType()
          this.getList()
        }).catch(() => {
          this.$message.info('取消删除')
        })
      },
      /** 导出按钮操作 */
      exportList() {
        // if(!this.queryParams.parentId){
        //   this.$message.warning('请选择设备分类')
        //   return
        // }
        this.$confirm('是否确认导出所有用户数据项?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          let res = await deviceTypeExport(this.queryParams)
          return this.download(res.data)
        }).catch(function() {
        })
      },
      /** 查询上级name 递归遍历 **/
      filtration(id) {
        let str = ''
        const getStr = function(data) {
          data.forEach(function(row) {
            if (row.id == id) {
              str = row.deviceName
            } else {
              if (row.list) {
                getStr(row.list)
              } else {
                if (row.id == id) {
                  str = row.deviceName
                }
              }
            }
          })
        }
        getStr(this.deptOptions)
        return str
      }
    }
  }
</script>
